package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.wxbean.TemplateData;
import com.qianniu.napi.admin.entity.wxbean.WxmappTemplate;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.admin.service.ITemplatemsgService;
import com.qianniu.napi.admin.service.ITplformService;
import com.qianniu.napi.admin.service.IUserService;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2019-03-11
 */
@Controller
public class TplformController {

    private static final Logger logger = LoggerFactory.getLogger(TplformController.class);

    @Autowired
    private ITplformService tplformService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ITemplatemsgService templatemsgService;

    @RequestMapping("/api/tplform/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = tplformService.selectPage(page, new EntityWrapper<Tplform>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/tplform/add")
    @ResponseBody
    public Jinfo tplformAdd(@Valid Tplform tplform,
                            BindingResult bindingResult, HttpServletRequest req) {
        Jinfo info = new Jinfo();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            info.setMsg("There are errors! " + bindingResult);
            info.setCode(400);
            return info;
        }

        User user = redisService.getUser();
        tplform.setFormdate(DateUtil.getToday());
        tplform.setCreatetime(new Date());

        MerchantConfig mconfig = redisService.getMconfig();
        if (mconfig.getIsFladmin() == 1) {
            MerchantApp mapp = redisService.getMApp(ObjectUtil.getMainmpid());
            tplform.setMid(mapp.getMid());
            tplform.setMpid(mapp.getId());
            User muser = userService.selectOne(new EntityWrapper<User>()
                    .eq("phone",user.getPhone())
                    .eq("mpid",ObjectUtil.getMainmpid()));

            tplform.setOpenid(muser.getOpenid());
            tplform.setUid(muser.getId());

        } else {

            tplform.setOpenid(user.getOpenid());
            tplform.setMid(ObjectUtil.getMid());
            tplform.setMpid(ObjectUtil.getMpid());
            tplform.setUid(ObjectUtil.getUid());
        }

        tplform.insert();
        return info;
    }

    @RequestMapping("/api/tplform/modify")
    @ResponseBody
    public Jinfo tplformUpdate(HttpServletRequest req,
                               Tplform tplform) {
        Jinfo info = new Jinfo();
        tplform.setModifytime(new Date());
        tplform.updateById();
        return info;
    }

    @RequestMapping("/api/tplform/sendTplmsg")
    @ResponseBody
    public Jinfo sendTplmsg() {
        Jinfo info = new Jinfo();
        Tplform tplform = tplformService.selectOne(new EntityWrapper<Tplform>()
                .eq("state", 1)
                .eq("uid", 336l)
                .orderBy("id"));

        Templatemsg templatemsg = templatemsgService.selectOne(new EntityWrapper<Templatemsg>()
                .eq("tplcode", "payok")
                .eq("mpid", 3)
                .orderBy("id"));

        List<TemplateData> tpllist = new ArrayList<TemplateData>();
        for (int i = 0; i < templatemsg.getKeysize(); i++) {

            if (i == 0) tpllist.add(new TemplateData("keyword1", "物品名称"));
            if (i == 1) tpllist.add(new TemplateData("keyword2", "2019年03月10日"));
            if (i == 2) tpllist.add(new TemplateData("keyword3", "100元"));
            if (i == 3) tpllist.add(new TemplateData("keyword4", "18810370168"));
            if (i == 4) tpllist.add(new TemplateData("keyword5", "朝阳区建国路91号金地中心"));
            if (i == 5) tpllist.add(new TemplateData("keyword6", "朝阳区建国路91号金地中心"));
            if (i == 6) tpllist.add(new TemplateData("keyword7", "13366732360"));
            if (i == 7) tpllist.add(new TemplateData("keyword8", "测试数据8"));
            if (i == 8) tpllist.add(new TemplateData("keyword9", "测试数据8"));
            if (i == 9) tpllist.add(new TemplateData("keyword10", "测试数据9"));
            if (i == 10) tpllist.add(new TemplateData("keyword11", "测试数据10"));
            if (i == 11) tpllist.add(new TemplateData("keyword12", "测试数据11"));

        }

        WxmappTemplate wxtpl = new WxmappTemplate();
        wxtpl.setTouser(tplform.getOpenid());
        wxtpl.setForm_id(tplform.getFormid());

        wxtpl.setTemplate_id(templatemsg.getTplid());
        wxtpl.setPage(templatemsg.getPage());
        wxtpl.setTemplateDataList(tpllist);

        ObjectUtil.sendTemplateMsg(redisService.getWxtoken(tplform.getMpid().toString()), wxtpl);

        tplform.setState(-1);
        tplform.setModifytime(new Date());
//        tplform.setModifier(new Date());
        tplform.updateById();

        return info;
    }

    @RequestMapping("/api/tplform/detail")
    @ResponseBody
    public Jinfo getTplformDetailById(@RequestParam("token") String token,
                                      @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Tplform tplform = tplformService.selectById(id);
        info.setInfo(tplform);
        return info;
    }
}
